//
//  WBNetworkManager+Entension.swift
//  Weibo
//
//  Created by apple on 2016/12/4.
//  Copyright © 2016年 yanjun. All rights reserved.
//

import Foundation

// MARK: - 封装网络请求方法
extension WBNetworkManager {
 
    
    /// 加载微博数据
    ///
    /// - Parameters:
    ///   - since_id: <#since_id description#>
    ///   - max_id: <#max_id description#>
    ///   - completion: <#completion description#>
    func statusList(since_id:Int64 = 0, max_id: Int64 = 0, completion: @escaping (_ list: [[String: Any]]?,_ isSuccess: Bool) -> ()) {
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        
        
        let params = ["since_id": since_id,"max_id": max_id > 0 ? (max_id - 1) : 0]
        
        
        tokenRequest(URLString: urlString, parameters: params, completion: { (json,isSuccess) -> () in
            
            
            // 从 json 中获取 statuses 字典数组
            let result = json?["statuses"] as? [[String: AnyObject]]
            
            completion(result, isSuccess)
            
            
        })
        
    }
    
    // 返回微博未读数量
    func unReadCount(competion: @escaping (_ count: Int) -> ()) {
        guard let uid = userAccount.uid else {
            return
        }
        
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        
        let params = ["uid": uid]
        
        tokenRequest(URLString: urlString, parameters: params, completion: { (json, isSuccess) in
            
            let dict = json as? [String: AnyObject]
            let count = dict?["status"] as? Int
            
            competion(count ?? 0)
            
        })
        
    }
    
}

// MARK: - 用户信息
extension WBNetworkManager {
    
    
    // 加载当前用户信息
    func loadUserInfo(completion:@escaping (_ dict: [String: Any]) -> ()) {
        
        guard let uid = userAccount.uid else {
            return
        }
        
        let urlSting = "https://api.weibo.com/2/users/show.json"
        
        let params = ["uid":uid]
        
        tokenRequest(URLString: urlSting, parameters: params, completion: { (json, isSuccess) in
        
            
            print("当前用户信息========\(json!)")
            
            completion((json as? [String: Any]) ?? [:] )
        
        })
        
        
    }
    
    
}

// MARK: - OAuth相关方法
extension WBNetworkManager {
    
    // 加载 AccessToken
    func loadAccessToken(code: String,completion:@escaping (_ isSuccess: Bool) -> ()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id":WBAPPKey,
                      "client_secret":WBAppSecret,
                      "grant_type":"authorization_code",
                      "code":code,
                      "redirect_uri":WBRedirectURI]
        
        
        request(method: .POST, URLString: urlString, parameters: params, completion: { (json, isSuccess) in
            
            // 如果请求失败，对用户账户数据不会有任何影响
            
            self.userAccount.yy_modelSet(with: (json as? [String : AnyObject]) ?? [:])
            
            // 加载当前用户信息
            self.loadUserInfo(completion: { (dict) in
                
                // 使用用户信息字典设置账户信息(昵称和头像地址)
                self.userAccount.yy_modelSet(with: dict)
                
                // 保存模型
                self.userAccount.saveAccount()

                
                // 用户信息加载完成再回调
                completion(isSuccess)
            })
            
            
        })
        
    }
    
    
    
}

